﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Awaken.Utils.WidgetCode
{
    /// <summary>
    /// 地理位置计算器
    /// </summary>
    public class EarthCalculator
    {
        /// <summary>
        /// 计算经纬度间的距离
        /// </summary>
        /// <param name="originLat"></param>
        /// <param name="originLng"></param>
        /// <param name="destinLat"></param>
        /// <param name="destinLng"></param>
        /// <param name="gs">默认：全球平均半径</param>
        /// <returns></returns>
        public static double DistanceOfTwoPoints(double originLat, double originLng, double destinLat, double destinLng, GaussSphere gs = GaussSphere.WGS84)
        {

            double radOriginLat = Rad(originLat);

            double radDestinLat = Rad(destinLat);

            double a = radOriginLat - radDestinLat;

            double b = Rad(originLng) - Rad(destinLng);

            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
                Math.Cos(radOriginLat) * Math.Cos(radDestinLat) * Math.Pow(Math.Sin(b / 2), 2)));

            s = s * (gs == GaussSphere.WGS84 ? 6378137.0 : (gs == GaussSphere.Xian80 ? 6378140.0 :6378245.0));

            s = Math.Round(s * 10000) / 10000;

            return s;
        }


        /// <summary>
        /// 计算角度
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private static double Rad(double d)
        {
            return d * Math.PI / 180.0;
        }


        /// <summary>
        /// 高斯投影中所选用的参考椭球
        /// </summary>
        public enum GaussSphere
        {
            Beijing54,
            Xian80,
            WGS84,
        }
    }
}
